import 'package:changxindianzishangwu/dao/title_dao.dart';
import 'package:changxindianzishangwu/model/address_book_model.dart';
import 'package:changxindianzishangwu/model/titles_list.dart';
import 'package:changxindianzishangwu/pages/my/settings/send_message_all_page.dart';
import 'package:changxindianzishangwu/provider/currentMessageList.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/fade_router.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/widget/loding.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart';
import 'package:get/utils.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';

import '../home_page.dart';
import 'create_titls_page.dart';

class ContactsTitilesPage extends StatefulWidget {
  int type;
  List<V2TimMessage> someMessage;
  List<AddressBookModel> someUser = [];
  ContactsTitilesPage({Key key, this.type = 1, this.someMessage, this.someUser})
      : super(key: key);

  @override
  _ContactsTitilesPageState createState() => _ContactsTitilesPageState();
}

class _ContactsTitilesPageState extends State<ContactsTitilesPage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    selectTitle();
  }

  TitleList titleList;
  List<Widget> itemWidget = [];
  selectTitle() async {
    itemWidget = [];
    titleList = await TitleDao.selectTitle();
    if (widget.type == 1) {
      itemWidget.add(
        Container(
          height: 60,
          color: Colors.white,
          alignment: Alignment.centerLeft,
          padding: EdgeInsets.only(left: 15.w),
          child: TextField(
            onTap: () {
              Get.to(() => CreateTitlsPage());
            },
            onChanged: (value) {
              print(value);
            },
            keyboardType: TextInputType.name,
            style: TextStyle(fontSize: 15.sp),
            cursorColor: Colors.greenAccent,
            readOnly: true,
            decoration: InputDecoration(
              icon: Icon(
                Icons.add_circle_outline,
                color: ZdColor.rgba(0, 220, 169, 1),
              ),
              hintText: "添加成员",
              hintStyle: TextStyle(
                  fontSize: 14.sp, color: ZdColor.rgba(0, 220, 169, 1)),
              border: InputBorder.none,
            ),
          ),
        ),
      );

      if (titleList.resultCode == 1) {
        titleList.data.forEach((element) {
          itemWidget.add(Slidable(
            actionPane: SlidableScrollActionPane(), //滑出选项的面板 动画
            actionExtentRatio: 0.25,
            closeOnScroll: true,
            secondaryActions: <Widget>[
              IconSlideAction(
                  caption: '删除',
                  color: Colors.red,
                  icon: Icons.delete,
                  closeOnTap: true,
                  onTap: () async {
                    var result = await TitleDao.deleteTitle(element.groupId);
                    if (result['resultCode'] == 1) {
                      showToast('删除成功～');
                      await selectTitle();
                      setState(() {});
                    }
                  }),
            ],

            child: ListTile(
                onTap: () {
                  Get.off(() => CreateTitlsPage(
                        type: 3,
                        groupName: element.groupName,
                        groupId: element.groupId,
                      ));
                },
                leading: Text(
                  element.groupName,
                  style: TextStyle(fontSize: 15.sp),
                ),
                title: Container(
                  alignment: Alignment.centerRight,
                  child: Text(
                    element.userIdList.length.toString() + "人",
                    style: TextStyle(
                        fontSize: 15.sp, color: ZdColor.rgba(153, 153, 153, 1)),
                  ),
                ),
                trailing: Icon(Icons.chevron_right)),
          ));
          itemWidget.add(Divider(
            height: 1,
            indent: width(10),
            endIndent: width(15),
          ));
        });
      }
    } else if (widget.type == 2) {
      if (titleList.resultCode == 1) {
        titleList.data.forEach((element) {
          itemWidget.add(
            ListTile(
                onTap: () {
                  if (element.userIdList.length > 0) {
                    element.userIdList.forEach((elements) async {
                      print("id------------------------------" + elements);
                      widget.someMessage.forEach((element) async {
                        if (element.elemType == 1) {
                          ///文字
                          V2TimValueCallback<V2TimMessage> res =
                              await TencentImSDKPlugin
                                  .v2TIMManager.v2TIMMessageManager
                                  .sendTextMessage(
                            text: element.textElem.text,
                            receiver: elements,
                          );

                          List<V2TimMessage> list =
                              new List.empty(growable: true);
                          V2TimMessage msg = res.data;
                          list.add(msg);
                          Provider.of<CurrentMessageListModel>(context,
                                  listen: false)
                              .addMessage("c2c_" + elements, list);
                        } else if (element.elemType == 3) {
                          ///图片
                          print("imageurl============" +
                              element.imageElem.imageList[0].url);
                          V2TimValueCallback<V2TimMessage> res =
                              await TencentImSDKPlugin.v2TIMManager
                                  .getMessageManager()
                                  .sendCustomMessage(
                                    data: element.imageElem.imageList[0].url,
                                    extension: "images",
                                    receiver: elements,
                                  );
                          List<V2TimMessage> list =
                              new List.empty(growable: true);
                          V2TimMessage msg = res.data;
                          list.add(msg);
                          Provider.of<CurrentMessageListModel>(context,
                                  listen: false)
                              .addMessage("c2c_" + elements, list);
                        } else if (element.elemType == 4) {
                          ///音频
                          if (GetPlatform.isAndroid) {
                            V2TimValueCallback<V2TimMessage> res =
                                await TencentImSDKPlugin
                                    .v2TIMManager.v2TIMMessageManager
                                    .sendSoundMessage(
                                        soundPath: element.soundElem.path,
                                        receiver: elements,
                                        duration: element.soundElem.duration);
                            List<V2TimMessage> list =
                                new List.empty(growable: true);
                            V2TimMessage msg = res.data;
                            list.add(msg);
                            Provider.of<CurrentMessageListModel>(context,
                                    listen: false)
                                .addMessage("c2c_" + elements, list);
                          } else {
                            V2TimValueCallback<V2TimMessage> res =
                                await TencentImSDKPlugin
                                    .v2TIMManager.v2TIMMessageManager
                                    .sendCustomMessage(
                                        data: element.soundElem.path,
                                        extension: "au",
                                        receiver: elements,
                                        desc: element.soundElem.duration
                                            .toString());
                            List<V2TimMessage> list =
                                new List.empty(growable: true);
                            V2TimMessage msg = res.data;
                            list.add(msg);
                            Provider.of<CurrentMessageListModel>(context,
                                    listen: false)
                                .addMessage("c2c_" + elements, list);
                          }
                        } else if (element.elemType == 5) {
                          ///视频
                          print("vo=========" + element.videoElem.videoUrl);
                          V2TimValueCallback<V2TimMessage> res =
                              await TencentImSDKPlugin
                                  .v2TIMManager.v2TIMMessageManager
                                  .sendCustomMessage(
                            data: element.videoElem.videoUrl,
                            extension: "mp4",
                            desc: element.videoElem.snapshotUrl,
                            priority: element.videoElem.duration,
                            receiver: elements,
                          );
                          List<V2TimMessage> list =
                              new List.empty(growable: true);
                          V2TimMessage msg = res.data;
                          list.add(msg);
                          Provider.of<CurrentMessageListModel>(context,
                                  listen: false)
                              .addMessage("c2c_" + elements, list);
                        }
                      });
                    });
                    Get.offAll(() => HomePage(
                          pageIndex: 0,
                        ));
                  } else {
                    Get.offAll(() => HomePage(
                          pageIndex: 0,
                        ));
                  }
                },
                leading: Text(
                  element.groupName,
                  style: TextStyle(fontSize: 15.sp),
                ),
                title: Container(
                  alignment: Alignment.centerRight,
                  child: Text(
                    element.userIdList.length.toString() + "人",
                    style: TextStyle(
                        fontSize: 15.sp, color: ZdColor.rgba(153, 153, 153, 1)),
                  ),
                ),
                trailing: Icon(Icons.chevron_right)),
          );
          itemWidget.add(Divider(
            height: 1,
            indent: width(10),
            endIndent: width(15),
          ));
        });
      }
    } else if (widget.type == 3) {
      if (titleList.resultCode == 1) {
        titleList.data.forEach((element) {
          itemWidget.add(
            ListTile(
                onTap: () {
                  List<AddressBookModel> someUser = [];
                  TencentImSDKPlugin.v2TIMManager
                      .getFriendshipManager()
                      .getFriendsInfo(userIDList: element.userIdList)
                      .then((value) {
                    value.data.forEach((el) {
                      someUser.add(AddressBookModel(
                          userId: el.friendInfo.userID,
                          name: el.friendInfo.friendRemark ??
                              el.friendInfo.userProfile.nickName,
                          headerUrl: el.friendInfo.userProfile.faceUrl));
                    });
                  });
                  element.userIdList.forEach((elements) {});

                  Get.off(() => SendMessageAllPage(
                        someUser: someUser,
                      )).then((value) => Get.back());
                },
                leading: Text(
                  element.groupName,
                  style: TextStyle(fontSize: 15.sp),
                ),
                title: Container(
                  alignment: Alignment.centerRight,
                  child: Text(
                    element.userIdList.length.toString() + "人",
                    style: TextStyle(
                        fontSize: 15.sp, color: ZdColor.rgba(153, 153, 153, 1)),
                  ),
                ),
                trailing: Icon(Icons.chevron_right)),
          );
          itemWidget.add(Divider(
            height: 1,
            indent: width(10),
            endIndent: width(15),
          ));
        });
      }
    }

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    if (titleList != null &&
        titleList.data != null &&
        titleList.resultCode == 1) {
      return Scaffold(
        appBar: AppBar(
          leading: IconButton(
            icon: Icon(Icons.arrow_back_ios),
            onPressed: () {
              Navigator.pushAndRemoveUntil(
                  context,
                  FadeRoute(HomePage(
                    pageIndex: 1,
                  )),
                  (route) => false);
            },
          ),
          elevation: 0,
          centerTitle: true,
          title: Text(
            "标签",
            style: TextStyle(fontSize: 16.sp),
          ),
        ),
        body: GestureDetector(
          onHorizontalDragUpdate: (details) {
            print("============${details.globalPosition.dx}");
            if (details.globalPosition.dx > 60 &&
                details.globalPosition.dx < 120) {
              Navigator.pushAndRemoveUntil(
                  context,
                  FadeRoute(HomePage(
                    pageIndex: 1,
                  )),
                  (route) => false);
            }
          },
          child: Container(
            height: double.infinity,
            color: Colors.white,
            child: ListView(
              shrinkWrap: true,
              children: itemWidget,
            ),
          ),
        ),
      );
    } else {
      return Loading();
    }
  }
}
